<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}"/>
    <link rel="stylesheet" th:href="@{/css/custom.form.css}">
    <style>
        .layui-upload-img {
            width: 92px;
            height: 92px;
        }
    </style>
</head>
<body>
<div class="panel panel-default operation" hidden>
    <div class="panel-heading title"></div>
    <div class="layui-card-body">
        <form class="layui-form " action="" lay-filter="info">
            <input name="id" hidden/>
            <div class="layui-form-item">
                <label class="layui-form-label">标题</label>
                <div class="layui-input-block">
                    <input type="title" name="title" placeholder="请输入标题" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">类型</label>
                <div class="layui-input-block">
                    <select id="type" name="type" lay-filter="select-type"
                            th:with="type=${@sysDictService.getType('content_type')}">
                        <option value="0">请选择</option>
                        <option th:each="dict : ${type}" th:text="${dict.label}" th:value="${dict.value}"></option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">关键字</label>
                <div class="layui-input-block" th:with="type=${@sysDictService.getType('content_keyword')}">
                    <input class="disabled" th:each="dict : ${type}" type="checkbox"
                           th:name="'keywords[' + ${dict.value} + ']'"
                           th:title="${dict.label}"></input>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">内容</label>
                <div class="layui-input-block">
                    <textarea id="content" name=content style="display: none;"></textarea>
                </div>
            </div>
            <div class="layui-upload">
                <button type="button" class="layui-btn disabled" id="multiImgButton"><i class="layui-icon">&#xe67c;</i>
                    多图展示
                </button>
                <div class="layui-upload-list" style="width:1000px;height: 120px;border: 1px solid"
                     id="multi-div"></div>
            </div>
            <div class="layui-form-item" style="margin-top:15px">
                <div class="layui-inline">
                    <div class="layui-upload">
                        <button type="button" class="layui-btn disabled" id="oneImgButton"><i class="layui-icon">&#xe67c;</i>单图展示
                        </button>
                        <div class="layui-upload-list" style="width:100px">
                            <img onclick="CoreUtil.showImg(this.src)" class="layui-upload-img" id="one-img">
                            <center>
                                <button onclick="emptyImgSrc('one-img');return false;"
                                        class="layui-btn disabled layui-btn-danger layui-btn-xs">删除
                                </button>
                            </center>
                        </div>

                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">保存</button>
                    <button class="layui-btn layui-btn-primary" id="btn_cancel">返回</button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="table_div">
    <div id="searchParam" shiro:hasPermission="sysContent:list">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <input type="text" id="title" class="layui-input" autocomplete="off" placeholder="请输入标题">
            </div>

            <div class="layui-input-inline ">
                <button class="layui-btn" onclick="search()">查询</button>
            </div>
        </div>

    </div>
    <table class="layui-table" id="showTable" lay-filter="showTable"></table>
</div>
<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add" shiro:hasPermission="sysContent:add">添加</button>
        <button class="layui-btn layui-btn-sm" lay-event="batchDeleted" shiro:hasPermission="sysContent:delete">删除
        </button>
    </div>
</script>
<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-xs" lay-event="preview" shiro:hasPermission="sysContent:list">预览</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit" shiro:hasPermission="sysContent:update">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" shiro:hasPermission="sysContent:delete">删除</a>
</script>

</body>
</html>
<script th:inline="javascript" type="text/javascript">
    var ctx = '[[@{/}]]'.replaceAll("\"", "").replace('//', '/');
</script>
<script th:src="@{/layui/layui.all.js}"></script>
<script th:src="@{/js/core.util.js}"></script>
<script>
    //文章类型字典数据
    var datas = "[[${@sysDictService.getType('content_type')}]]".replace(/&quot;/g, "\"");
    //获取token
    var token = CoreUtil.getData("access_token");
    //地址栏转义token中的#号
    var tokenQuery = token.replace("#", "%23");
    var tableIns1;
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = jQuery = layui.jquery;
    var laydate = layui.laydate;
    var layedit = layui.layedit;
    var upload = layui.upload;
    layui.use(['table', 'layer', 'laydate', 'layedit','upload'], function () {
        //图片
        layedit.set({
            uploadImage: {
                url: ctx + 'sysFiles/upload?authorization=' + tokenQuery //接口url
                , type: 'post' //默认post
            }
        });
        //建立富文本编辑器
        var editIndex = layedit.build('content');
        //加载table
        tableIns1 = table.render({
            elem: '#showTable'
            , contentType: 'application/json'
            , headers: {"authorization": token}
            , page: true //开启分页
            , url: ctx + 'sysContent/listByPage' //数据接口
            , method: 'POST'
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                    "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
                }
            }
            , cols: [
                [
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'id', sort: true},
                    {field: 'title', title: '标题', sort: true},
                    {
                        field: 'type', title: '类型', sort: true, templet: function (item) {
                            //获取类型对应的字典label
                            return CoreUtil.selectDictLabel(datas, item.type);
                        }
                    },
                    {field: 'content', title: '内容', sort: true},
                    {field: 'createTime', title: '创建时间', sort: true},
                    {width: 200, toolbar: "#tool", title: '操作'}
                ]
            ]
            , toolbar: '#toolbar'
        });

        //表头工具
        table.on('toolbar(showTable)', function (obj) {
            switch (obj.event) {
                case 'batchDeleted':
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    if (data.length == 0) {
                        layer.msg("请选择要批量删除的列");
                    } else {
                        var ids = [];
                        $(data).each(function (index, item) {
                            ids.push(item.id);
                        });
                        tipDialog(ids);
                    }
                    break;
                case 'add':
                    $(".table_div").hide();
                    $(".operation").show();
                    $(".title").html("新增");
                    form.val('info', {
                        "id":"",
                        "title": "",
                        "type": "0"
                    })
                    layedit.setContent(editIndex, "");
                    //渲染select 默认选中第一个
                    //图片
                    emptyImgSrc("one-img");
                    $('#multi-div').empty();
                    break;
            }
            ;
        });
        //列操作
        table.on('tool(showTable)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'del':
                    var ids = [];
                    ids.push(data.id);
                    tipDialog(ids);
                    break;
                case 'edit':
                    $(".table_div").hide();
                    $(".operation").show();
                    $(".title").html("编辑");
                    form.val('info', {
                        "id": data.id,
                        "title": data.title,
                        "type": data.type
                    })
                    layedit.setContent(editIndex, data.content);
                    //复选框回显
                    form.val('info', CoreUtil.setCheckboxValues("keywords", data.keywords));
                    //单图回显
                    $('#one-img').attr('src', data.oneImg);
                    //多图回显
                    $('#multi-div').empty();
                    if (!CoreUtil.isEmpty(data.multipleImg)) {
                        var arr = data.multipleImg.split(",");
                        for (var i = 0; i < arr.length; i++) {
                            $('#multi-div').append(buildMutiImgHtml(i, arr[i]))
                        }
                    }
                    break;
                case 'preview':
                    layer.open({
                        type: 1,
                        skin: 'layui-layer-demo', //样式类名
                        title: "预览",
                        shadeClose: true, //开启遮罩关闭
                        area: ['900px', '500px'], //宽高
                        shade: 0.6, //遮罩透明度
                        maxmin: true, //允许全屏最小化
                        anim: 1, //0-6的动画形式，-1不开启
                        content: data.content, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        cancel: function () {
                        }
                    });
                    break;
            }
        });


        //删除
        var tipDialog = function (ids) {
            layer.open({
                content: "确定要删除么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendDelete(ctx + "sysContent/delete", ids, function (res) {
                        layer.msg(res.msg, {time: 1000}, function () {
                            search();
                        });
                    })
                }
            });
        };

        //返回
        $("#btn_cancel").click(function () {
            $(".table_div").show();
            $(".operation").hide();
            return false;
        });

        //监听保存
        form.on('submit(submit)', function (data) {
            //获取复选框的值
            data.field.keywords = CoreUtil.getCheckboxValues("keywords", data.field);
            //单图
            data.field.oneImg = $("#one-img").attr("src");
            //多图
            var urlAll = "";
            $(".multi-img").each(function (index, element) {
                if (index === 0) {
                    urlAll = $(this).attr("src");
                } else {
                    urlAll = urlAll + "," + $(this).attr("src");
                }
            });
            data.field.multipleImg = urlAll;
            //图文
            data.field.content = layedit.getContent(editIndex);
            if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
                CoreUtil.sendPost(ctx + "sysContent/add", data.field, function (res) {
                    $(".table_div").show();
                    $(".operation").hide();
                    search();
                })
            } else {
                CoreUtil.sendPut(ctx + "sysContent/update", data.field, function (res) {
                    $(".table_div").show();
                    $(".operation").hide();
                    search();
                })
            }

            return false;
        });


        //多图上传
        upload.render({
            elem: '#multiImgButton'
            , url: ctx + 'sysFiles/upload?authorization=' + tokenQuery //此处配置你自己的上传接口即可
            , multiple: true
            , acceptMime: 'image/*'
            , done: function (res) {
                $('#multi-div').append(buildMutiImgHtml(res.data.id, res.data.src))
            }
        });

        //单图上传
        upload.render({
            elem: '#oneImgButton'
            , url: ctx + 'sysFiles/upload?authorization=' + tokenQuery //此处配置你自己的上传接口即可
            , multiple: false
            , acceptMime: 'image/*'
            , done: function (res) {
                $('#one-img').attr('src', res.data.src); //图片链接（base64）
            }
        });
    });


    //构建多图片上传html
    function buildMutiImgHtml(id, src) {
        return '<div id="' + id + '" style="float:left">' +
            '<img onclick="CoreUtil.showImg(this.src)" src="' + src + '" class="layui-upload-img multi-img">' +
            '<br><center><button class="layui-btn disabled layui-btn-danger layui-btn-xs" ' +
            'onclick="removeImg(\'' + id + '\')">删除</button></center></div>'
    }

    //多图片上传， 删除图片
    function removeImg(id) {
        $("#" + id).remove();
    }

    //单图片，清空
    function emptyImgSrc(id) {
        $('#' + id).removeAttr("src"); //图片链接（base64）
    }


    //执行查询
    function search() {
        //这里以搜索为例
        tableIns1.reload({
            where: { //设定异步数据接口的额外参数，任意设
                title: $("#title").val()
            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    };
</script>